package com.answerz.module_reportissues.viewmodel

import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.TimeUtils
import com.czl.base.base.BaseBean
import com.czl.base.base.BaseViewModel
import com.czl.base.base.MyApplication
import com.czl.base.binding.command.BindingAction
import com.czl.base.binding.command.BindingCommand
import com.czl.base.config.AppConstants
import com.czl.base.data.DataRepository
import com.czl.base.data.bean.OrderDetailBean
import com.czl.base.data.bean.RepairListBean
import com.czl.base.data.bean.ReportOrderState
import com.czl.base.event.LiveBusCenter
import com.czl.base.event.SingleLiveEvent
import com.czl.base.extension.ApiSubscriberHelper
import com.czl.base.util.RxThreadHelper
import com.luck.picture.lib.entity.LocalMedia
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class OrderDetailViewmodel(application: MyApplication, model: DataRepository) :
    BaseViewModel<DataRepository>(application, model) {
    var orderNo = ObservableField<String>("")
    var reportLocation = ObservableField<String>("")
    var reportPersen = ObservableField<String>("")
    var reportPhone = ObservableField<String>("")
    var orderResponsible = ObservableField<String>("")
    var orderMaintain = ObservableField<String>("")
    var orderMaintainPhone = ObservableField<String>("")
    var orderContent = ObservableField<String>("")
    var orderAttach = ObservableField<ArrayList<LocalMedia>>(ArrayList<LocalMedia>())
    var orderState = ObservableField<String>("")
    var orderStateFlow = ObservableField<ArrayList<ReportOrderState>>()
    var orderButtonText = ObservableField<String>("")
    var orderPrice = ObservableField<String>("")
    var attachImagesEvent: SingleLiveEvent<ArrayList<LocalMedia>> = SingleLiveEvent()
    var orderStateFlowEvent: SingleLiveEvent<ArrayList<ReportOrderState>> = SingleLiveEvent()
    val refreshListEvent: SingleLiveEvent<Void> = SingleLiveEvent()
    val loadCompleteEvent: SingleLiveEvent<RepairListBean> = SingleLiveEvent()
    val cancelOrderEvent: SingleLiveEvent<String> = SingleLiveEvent()
    val deleteOrderEvent: SingleLiveEvent<String> = SingleLiveEvent()
    val navScoreEvent: SingleLiveEvent<String> = SingleLiveEvent()
    var onClickSubmit: BindingCommand<Any> = BindingCommand(BindingAction {
        dealOrder(orderButtonText.get().toString(), orderNo.get().toString())
    })
    val onClickPay: BindingCommand<Void> = BindingCommand(BindingAction {
        var payInfo = GsonUtils.toJson(
            mapOf(
                "no" to orderNo.get(),
                "payAmount" to orderPrice.get(),
                "areaId" to model.getAreaId()
            )
        )
        startContainerActivity(AppConstants.Router.Pay.F_PAY_DETAIL, Bundle().apply {
            putString(AppConstants.BundleKey.PAY_ORDER_KEY, payInfo)
            putString(AppConstants.BundleKey.WORK_ORDER_IS, AppConstants.Constants.IS_WORK_ORDER)
        })
    })
    val onRefreshListener: BindingCommand<Void> = BindingCommand(BindingAction {
        getData(orderNo.get().toString())
    })
    val onRefreshFinishEvent:SingleLiveEvent<Boolean> = SingleLiveEvent()


    fun hasAttach(pl: ArrayList<LocalMedia>): Boolean {
        if (pl == null || pl.size == 0) {
            return false
        }
        return true
    }

    fun getData(no: String) {
        model.getOrderDetail(no)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<OrderDetailBean>>() {
                override fun onResult(t: BaseBean<OrderDetailBean>) {
                    dismissLoading()
                    if (t.code == 200) {
                        onRefreshFinishEvent.postValue(true)
                        var orderDetail = t.data
                        orderNo.set(orderDetail?.no)
                        reportLocation.set(orderDetail?.location)
                        reportPersen.set(orderDetail?.reporterName)
                        reportPhone.set(orderDetail?.reporterMobile)
                        orderResponsible.set(orderDetail?.handlerName)
                        orderMaintain.set(orderDetail?.repairerName)
                        orderMaintainPhone.set(orderDetail?.repairerMobile)
                        orderContent.set(orderDetail?.description)
                        var photolist = ArrayList<LocalMedia>()
                        for (item in orderDetail?.files!!) {
                            photolist.add(LocalMedia().apply { path = item
                                mimeType= if (item.endsWith(".mp4")) "video/mp4" else ""})
                        }
                        orderAttach.set(photolist)
                        attachImagesEvent.postValue(photolist)
                        var sls = ArrayList<ReportOrderState>()
                        for (item in orderDetail.operLogs) {
//                                if (TextUtils.equals(item.title,"待接单")
//                                    || TextUtils.equals(item.title,"已接单")
//                                    || TextUtils.equals(item.title,"处理完成")
//                                    || TextUtils.equals(item.title,"已审核")
//                                    || TextUtils.equals(item.title,"已评价")) {
                            var img=ArrayList<LocalMedia>()
                            if (item.files!=null&& item.files!!.isNotEmpty()){
                                for (i in item.files!!){
                                    img.add(LocalMedia().apply {
                                        path=i
                                        mimeType= if (i.endsWith(".mp4")) "video/mp4" else ""
                                    })
                                }
                            }
                            sls.add(
                                ReportOrderState(
                                    item.title, item.score, "", item.statusDescription,
                                    formatDateString(item.createTime), item.memo, img
                                )
                            )
//                                }
                        }
                        setButtonText(appenState(sls, orderDetail.status), orderDetail.serviceFee)
                        orderStateFlowEvent.postValue(sls)
                    } else {
                        onRefreshFinishEvent.postValue(false)
                        showErrorToast(t.msg)
                    }
                }

                override fun onFailed(msg: String?) {
                    onRefreshFinishEvent.postValue(false)
                    dismissLoading()
                    showErrorToast(msg)
                }
            })
    }

    fun formatDateString(time: String): String {
        if (TextUtils.isEmpty(time)) {
            return ""
        }
        var df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
        var df1 = SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK)
        var df2 = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        var date = df.parse(time)
        var date1 = df1.parse(date.toString())
        var date2 = df2.format(date1)
//        var date3=df2.format(date)
        return date2

    }

    fun appenState(sls: ArrayList<ReportOrderState>, state: Int): String {
        when (state) {
            0 -> {
                return "待接单"
            }
            1 -> {
                sls.add(ReportOrderState("处理中", 0.0, "", "", "", "", null))
                return "处理中"
            }
            2 -> {
                sls.add(ReportOrderState("待审核", 0.0, "", "", "", "", null))
                return "待审核"
            }
            3 -> {
                sls.add(ReportOrderState("待支付", 0.0, "", "", "", "", null))
                return "待支付"
            }
            4 -> {
                sls.add(ReportOrderState("待评价", 0.0, "", "", "", "", null))
                return "待评价"
            }
            5 -> {
                return "已评价"
            }
        }
        return ""
    }

    fun setButtonText(state: String, price: Double) {
        orderButtonText.set("")
        orderPrice.set("")
        when (state) {
            "待接单" -> orderButtonText.set("撤销")
            "处理中" -> orderButtonText.set("撤销")
            "待支付" -> orderPrice.set(price.toString())
            "待评价" -> orderButtonText.set("评价")
            "已评价" -> orderButtonText.set("删除")

        }
    }

    fun dealOrder(state: String, orderNo: String) {
        when (state) {
            "撤销" -> cancelOrderEvent.postValue(orderNo)
            "支付" -> showNormalToast("支付")
            "评价" -> navScoreEvent.postValue(orderNo)
            "删除" -> deleteOrderEvent.postValue(orderNo)
        }
    }

    fun cancelWorkOrder(no: String) {
        model.cancelWorkOrder(no)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    dismissLoading()
                    if (t.code == 200) {
                        LiveBusCenter.postCancelOrderEvent(no)
                        showSuccessToast("撤销成功！")
                    } else {
                        showSuccessToast("撤销失败！")
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    fun deleteWorkOrder(no: String) {
        model.deleteWorkOrder(no)
            .compose(RxThreadHelper.rxSchedulerHelper(this))
            .doOnSubscribe { showLoading() }
            .subscribe(object : ApiSubscriberHelper<BaseBean<Any?>>() {
                override fun onResult(t: BaseBean<Any?>) {
                    dismissLoading()
                    if (t.code == 200) {
                        LiveBusCenter.postDeleteOrderEvent(no)
                        showSuccessToast("删除成功！")
                    } else {
                        showSuccessToast("删除失败！")
                    }
                }

                override fun onFailed(msg: String?) {
                    dismissLoading()
                    showErrorToast(msg)
                }

            })
    }

    fun setOrderState(state: String) {
        var buttonMap = mapOf(
            "待接单" to "接单",
            "处理中" to "处理完成",
            "待支付" to "",
            "待审核" to "",
            "待评价" to "",
            "已评价" to ""
        )
        orderButtonText.set(buttonMap[state])
        var stateMap = mapOf(
            "待接单" to ReportOrderState("待接单", 0.0, "", "", "", "", null),
            "处理中" to ReportOrderState("处理中", 0.0, "", "", "", "", null),
            "待支付" to ReportOrderState("待支付", 0.0, "", "", "", "", null),
            "待审核" to ReportOrderState("待审核", 0.0, "", "", "", "", null),
            "待评价" to ReportOrderState("待评价", 0.0, "", "", "", "", null)
        )
        var photolist = ArrayList<LocalMedia>()
        photolist.add(LocalMedia().apply {
            path = "https://scpic.chinaz.net/files/pic/pic9/202009/apic27858.jpg"
        })
        photolist.add(LocalMedia().apply {
            path =
                "https://pic1.zhimg.com/v2-d58ce10bf4e01f5086c604a9cfed29f3_r.jpg?source=1940ef5c"
        })
        photolist.add(LocalMedia().apply {
            path =
                "https://www.wanmeizy.com/uploads/ueditor/upload/image/20190513/155771589064749921.jpg"
        })
        photolist.add(LocalMedia().apply {
            path =
                "https://www.wanmeizy.com/uploads/ueditor/upload/image/20190513/155771589037954032.jpg"
        })
        orderAttach.set(photolist)
        attachImagesEvent.postValue(photolist)
        var stateList = ArrayList<ReportOrderState>()
        stateList.add(ReportOrderState("待接单", 0.0, "", "", "2021-11-11 11:11:11", "", null))
        stateList.add(
            ReportOrderState(
                "已接单",
                0.0, "", "王二已接单", "2021-11-11 11:11:11", "我预计30分钟内到达", null
            )
        )
        stateList.add(
            ReportOrderState(
                "处理完成",
                0.0, "", "王二已完成水管修改", "2021-11-11 11:11:11", "水管已维修完成", photolist
            )
        )
        stateList.add(ReportOrderState("已支付", 0.0, "", "李四已完成支付", "2021-11-11 11:11:11", "", null))
        stateList.add(ReportOrderState("已评价", 0.0, "服务好", "", "2021-11-11 11:11:11", "", null))
        var sls = ArrayList<ReportOrderState>()
        when (state) {
            "待接单" -> {
                sls.add(stateList[0])
            }
            "处理中" -> {
                sls.add(stateList[0])
                sls.add(stateList[1])
                stateMap[state]?.let { sls.add(it) }
            }
            "待支付" -> {
                sls.add(stateList[0])
                sls.add(stateList[1])
                sls.add(stateList[2])
                stateMap[state]?.let { sls.add(it) }
            }
            "待审核" -> {
                sls.add(stateList[0])
                sls.add(stateList[1])
                sls.add(stateList[2])
                stateMap[state]?.let { sls.add(it) }
            }
            "待评价" -> {
                sls.add(stateList[0])
                sls.add(stateList[1])
                sls.add(stateList[2])
                sls.add(stateList[3])
                stateMap[state]?.let { sls.add(it) }
            }
            "已评价" -> {
                sls.add(stateList[0])
                sls.add(stateList[1])
                sls.add(stateList[2])
                sls.add(stateList[3])
                sls.add(stateList[4])
            }
        }
        orderStateFlowEvent.postValue(sls)
    }

}